import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:example/utils/common.dart';
import 'package:get/get.dart';

class CustomNavigatorObserver extends NavigatorObserver {
  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    _pageStart(route, previousRoute);
    super.didPush(route, previousRoute);
  }

  @override
  void didReplace({Route? newRoute, Route? oldRoute}) {
    _pageStart(newRoute, oldRoute);
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
  }

  @override
  void didPop(Route route, Route? previousRoute) {
    _pageEnd(route, previousRoute);
    super.didPop(route, previousRoute);
  }

  /// 进入页面
  void _pageStart(Route<dynamic>? route, Route<dynamic>? previousRoute) {
    String? routeTitle;
    String? previousRouteTitle;
    if (route is GetPageRoute) {
      routeTitle = route.parameter?["title"];
    }
    if (previousRoute is GetPageRoute) {
      previousRouteTitle = previousRoute.parameter?["title"];
    }
    // 首次加载
    bool isFirst = routeTitle == "/" && previousRoute == null;
    if (!isFirst &&
        (isEmptyOrNull(routeTitle) || isEmptyOrNull(previousRouteTitle))) {
      return;
    }

    var arguments = route?.settings.arguments;

    // 横屏
    if (arguments != null &&
        arguments is Map &&
        arguments["isLandscape"] == true) {
      if (Platform.isAndroid) {
        SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
            overlays: [SystemUiOverlay.bottom]);

        SystemChrome.setPreferredOrientations([
          DeviceOrientation.landscapeLeft,
        ]);
      } else {
        SystemChrome.setPreferredOrientations([
          DeviceOrientation.landscapeRight,
        ]);
      }
    }
  }

  /// 离开页面
  _pageEnd(Route<dynamic>? route, Route<dynamic>? previousRoute) {
    String? routeTitle;
    String? previousRouteTitle;
    if (route is GetPageRoute) {
      routeTitle = route.parameter?["title"];
    }
    if (previousRoute is GetPageRoute) {
      previousRouteTitle = previousRoute.parameter?["title"];
    }
    // 首次加载
    bool isFirst = routeTitle == "/" && previousRoute == null;
    if (!isFirst &&
        (isEmptyOrNull(routeTitle) || isEmptyOrNull(previousRouteTitle))) {
      return;
    }

    var arguments = route?.settings.arguments;
    dynamic name = previousRoute?.settings.name;

    // 横屏
    if (arguments != null &&
        arguments is Map &&
        arguments["isLandscape"] == true) {
      if (Platform.isAndroid) {
        SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
            overlays: SystemUiOverlay.values);
      }
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
        DeviceOrientation.portraitDown,
      ]);
    }
  }
}
